package cmd

import (
	"fmt"
	"gosh/config"
	"gosh/pkg/proxy"
	"os"
	"time"

	"github.com/spf13/cobra"
)

// proxyCmd represents the proxy command
var proxyCmd = &cobra.Command{
	Use:   "proxy -H host [flags] [-l local] -r remote",
	Short: "将远程服务TCP端口代理到本地",
	Long: `将远程服务TCP端口代理到本地,方便服务调测。使用ssh工具实现本地端口转发和远程端口转发
可参考文档：https://www.yuque.com/duduniao/linux/nwsn6p#Kt3rn`,
	Args: cobra.NoArgs,
	Run: func(cmd *cobra.Command, args []string) {
		if err := config.ProxyInfo.Parse(); err != nil {
			fmt.Println(err.Error())
			os.Exit(1)
		}
		proxy.Run()
	},
}

func init() {
	rootCmd.AddCommand(proxyCmd)
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.Host, "host", "H", "", "转发请求的远程主机")
	proxyCmd.Flags().IntVarP(&config.ProxyInfo.Port, "port", "p", 22, "指定远程主机ssh的端口")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.User, "user", "u", "", "远程ssh用户,默认当前用户")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.Password, "password", "P", "", "远程ssh用户的密码")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.Key, "key", "k", "~/.ssh/id_rsa", "指定ssh私钥")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.KeyPassphrase, "key.passphrase", "", "", "ssh私钥的密码")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.BastionHost, "bastion.host", "j", "", "指定跳板机IP")
	proxyCmd.Flags().IntVarP(&config.ProxyInfo.BastionPort, "bastion.port", "", 22, "指定跳板机SSH端口")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.BastionUser, "bastion.user", "", "", "指定跳板机SSH用户,默认当前用户")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.BastionPassword, "bastion.password", "", "", "指定跳板机密码")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.BastionKey, "bastion.key", "", "~/.ssh/id_rsa", "指定跳板机ssh私钥")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.BastionKeyPassphrase, "bastion.key.passphrase", "", "", "指定跳板机ssh私钥的密码")
	proxyCmd.Flags().DurationVarP(&config.ProxyInfo.ConnectTimeout, "timeout", "t", time.Second*5, "连接超时时间,ssh连接和proxy转发超时")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.LocalAddress, "local", "l", "127.0.0.1:10080", "本地监听端口")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.RemoteAddress, "remote", "r", "", "目标服务地址")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.Protocol, "protocol", "", "tcp4", "远程服务器的通宵协议,tcp,tcp4,tcp6,unix")
	proxyCmd.Flags().StringVarP(&config.ProxyInfo.Type, "type", "", "local", "指定端口转发类型，local:本地端口转发，remote:远程端口转发")
	_ = proxyCmd.MarkFlagRequired("remote")
}
